const { getUserInfo, createUser, deleteUser, updateUser } = require("../services/user");
const { SuccessModel, ErrorModel } = require("../model/ResModel");
const { pwdCrypto } = require("../utils/cryp");

/**
 *
 * @param {用户名} userName
 */
async function isExist(userName) {
  const userInfo = await getUserInfo(userName);
  if (userInfo) {
    return new SuccessModel(userInfo);
  } else {
    return ErrorModel.registerUserNameNotExistInfo();
  }
}

/**
 * 注册
 * @param {string} userName
 * @param {string} password 密码
 * @param {number} gender 性别 (1 男， 2 女， 3 保密)
 */
async function register({ userName, password, gender }) {
  const userInfo = await getUserInfo(userName);
  if (userInfo) {
    return ErrorModel.registerUsernameExistInfo;
  }

  // 注册 service
  try {
    await createUser({
      userName,
      password: pwdCrypto(password),
      gender,
    });
    return new SuccessModel();
  } catch (err) {
    console.log(err.message, err.stack);
    return ErrorModel.registerFailInfo();
  }
}

/**
 *
 * @param {object} ctx
 * @param {string} userName
 * @param {string} password
 */
async function login(ctx, userName, password) {
  const userInfo = await getUserInfo(userName, pwdCrypto(password));
  if (!userInfo) {
    return ErrorModel.loginFailInfo();
  }
  ctx.session.userInfo = userInfo;
  return new SuccessModel();
}

/**
 * 删除当前用户
 * @param {Object} ctx context
 * @returns
 */
async function deleteCurUser(ctx) {
  if (
    process.env.NODE_ENV === "dev" &&
    ctx.session.userInfo &&
    ctx.session.userInfo.userName
  ) {
    const result = await deleteUser(ctx.session.userInfo.userName);
    if (result) {
      return new SuccessModel();
    }
  }
  return ErrorModel.deleteUserFailInfo();
}

/**
 * 修改用户信息
 * @param {*} ctx 
 * @param {*} param1 
 * @returns 
 */
async function changeUserInfo(ctx, { nickName, city, picture }) {
  const { userName } = ctx.session.userInfo
  const res = await updateUser({
    newNickName: nickName,
    newCity: city,
    newPicture: picture
  }, {
    userName
  })
  if(res) {
    Object.assign(ctx.session.userInfo, {
      nickName,
      city,
      picture
    })
    return new SuccessModel()
  }
  return ErrorModel.changeInfoFailInfo()
}

/**
 * 修改用户密码
 * @param {*} ctx 
 * @param {*} newPassword 
 */
async function changePassword(ctx, password, newPassword) {
  const { userName } = ctx.session.userInfo
  const res = await updateUser({
    newPassword: pwdCrypto(newPassword)
  }, {
    userName,
    password: pwdCrypto(password)
  })
  if(res) {
    return new SuccessModel()
  }
  return ErrorModel.changePasswordFailInfo()
}

async function logout(ctx) {
  delete ctx.session.userInfo
  return new SuccessModel()
}

module.exports = {
  isExist,
  register,
  login,
  deleteCurUser,
  changeUserInfo,
  changePassword,
  logout
};
